package com.bhcj.telling.presenter;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class ShakeListener implements SensorEventListener {

    private SensorManager sensorManager;
    private Sensor sensor;

    private long timeInterval = 10;
    private long lastTime = 100;
    private float lastX = 0;
    private float lastY = 0;
    private float lastZ = 0;
    private boolean isInitPosition = false;
    private double acceleration = 1000;
    private ShakeOnChangedListener shakeOnChangedListener;
    private Context context;

    public ShakeListener(Context c) {
        context = c;
    }

    public void setShakeOnChangedListener(ShakeOnChangedListener shakeOnChangedListener){
        this.shakeOnChangedListener = shakeOnChangedListener;
    }

    public void start() {
        sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        if (sensorManager != null) {
            sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        }
        if (sensor != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
        }
    }

    public void stop() {
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        try {
            long currentTime = System.currentTimeMillis();
            if (timeInterval > currentTime - lastTime) {
                return;//如果两次回调间隔过小，直接忽略
            }
            //读取传感器监听到加速度 m/(s^2)
            float[] values = event.values;
            if (!isInitPosition) {
                //手机的状态不同，其x,y,z的值不同，重新对x,y,z赋值
                lastX = values[0];
                lastY = values[1];
                lastZ = values[2];
                //仅限在初始化赋值
                isInitPosition = true;
            }
            float x = values[0];
            float y = values[1];
            float z = values[2];

            //计算和上次的变化值
            float deltaX = x - lastX;
            float deltaY = y - lastY;
            float deltaZ = z - lastZ;

            //更新变化值
            lastX = x;
            lastY = y;
            lastZ = z;
            //计算灵敏度 m/(s^3)
            double speed = (Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ) / timeInterval) * 1000;
            if (speed > acceleration) {
                if(shakeOnChangedListener != null){
                    shakeOnChangedListener.onChange(lastX,lastY,lastZ);
                }
                lastTime = System.currentTimeMillis();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
